﻿using System;
using UnityEngine;
namespace Core
{
    public class Bullet : Entity, IAwake<BulletConfig, Unit>, IFixedUpdate
    {
        public Unit caster;
        public BulletConfig config;
        protected MoveAgent moveAgent;
        protected Transform model;

        void IAwake<BulletConfig, Unit>.Awake(BulletConfig bulletConfig, Unit caster)
        {
            this.caster = caster;
            this.config = bulletConfig;

            var moveAgentType = config.moveAgent ?? "BulletNormalMoveAgent";
            var type = World.GetComponent<CodeTypes>().GetType(moveAgentType);
            moveAgent = Activator.CreateInstance(type) as MoveAgent;
            moveAgent.Attach(this);

            if (!string.IsNullOrEmpty(bulletConfig.path))
            {
                var prefab = World.GetComponent<ResourceComponent>().Load<GameObject>(bulletConfig.path);
                if (prefab != null)
                {
                    model = GameObject.Instantiate(prefab).transform;
                }
            }
        }

        public void Launch(Vector3 position, Vector3 orientation)
        {
            moveAgent.Start(position, orientation);
        }

        public void SetPosition(Vector3 position)
        {
            if(model != null)
            {
                model.position = position;
            }
        }

        public void SetRotate(Quaternion rotate)
        {
            if(model != null)
            {
                model.rotation = rotate;
            }
        }

        void IFixedUpdate.FixedUpdate()
        {
            if (moveAgent == null)
                return;

            var result = moveAgent.Update();

            if(moveAgent.MoveResult.hit == true)
            {
                foreach (var target in moveAgent.MoveResult.targets) 
                {
                    DamageCalculator.DamageBySkill(caster, target, this);
                }
            }
            
            if (result != BulletMoveStatus.Stop)
                return;

            this.Dispose();
        }

        public override void Dispose()
        {
            base.Dispose();

            caster = null;
            config = null;
            moveAgent = null;
            if (model != null)
            {
                GameObject.Destroy(model.gameObject);
            }
        }
    }


}